package com.poetry.common.entity.common;

import com.poetry.common.constant.KVConstant;
import com.poetry.common.constant.StatusConstant;
import com.poetry.common.util.IConstant;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;

/**
 * 通用返回
 * @param <T> 泛型
 */
//@Data
@AllArgsConstructor
@NoArgsConstructor
//@ToString
public class R<T> {
    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public boolean isSuccess() {
        return success;
    }

    public void setSuccess(boolean success) {
        this.success = success;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    @ApiModelProperty(value = "状态码", required = true)
    private int code;

    @ApiModelProperty(value = "是否成功", required = true)
    private boolean success;

    @ApiModelProperty("承载数据")
    private T data;

    @ApiModelProperty(value = "返回消息", required = true)
    private String msg;

    private R(int code, String msg){
        this(code, true, null, msg);
    }

    private R(int code, boolean success, String msg){
        this(code, success, null, msg);
    }

    private R(IConstant constant){
        this(constant, true);
    }

    private R(IConstant constant, boolean success){
        this(constant.getCode(), success, null, constant.getMsg());
    }

    public static <T> R<T> success(){
        return new R<>(KVConstant.SAVE_SUCCESS);
    }

    public static <T> R<T> deleteSuccess(){
        return new R<>(KVConstant.DELETE_SUCCESS);
    }

    public static <T> R<T> success(String msg){
        return new R<>(200, msg);
    }

    public static <T> R<T> msg(String msg){
        R<T> r = getSuccess();
        r.setMsg(msg);
        return r;
    }

    public static <T> R<T> data(T t){
        R<T> r = getSuccess();
        r.setData(t);
        return r;
    }

    public static <T> R<T> fail(String msg){
        return fail(StatusConstant.ERROR, msg);
    }

    public static <T> R<T> fail(int code, String msg){
        return new R<>(code, false, msg);
    }

    private static <T> R<T> getSuccess(){
        R<T> res = new R<>();
        res.setCode(StatusConstant.SUCCESS);
        return res;
    }
}
